﻿#region License
/* ---------------------------------------------------------------- *
 *
 * This file is part of the Xcoordination Application Space
 * ("XcoAppSpace") http://www.xcoordination.com
 *
 * Copyright (C) 2009 Xcoordination http://www.xcoordination.com
 *
 * XcoAppSpace is free software; you can redistribute it and/or
 * modify it under the terms of version 2 of the GNU General
 * Public License as published by the Free Software Foundation.
 *
 * XcoAppSpace is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/
 * or write to the Free Software Foundation, Inc., 51 Franklin
 * Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * ---------------------------------------------------------------- */
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Ccr.Core;

namespace XcoAppSpaces.Core
{
	/// <summary>
	/// Helper methods for getting and setting the current causalities.
	/// </summary>
	static class CausalityHelpers
	{
        public static IEnumerable<ICausality> ListOfActiveCausalities
        {
            get
            {
                List<ICausality> causalities = new List<ICausality>();

                CollectCausalitiesThroughRemoval(causalities);
                ReinstateCausalities(causalities);

                return causalities;
            }
        }

        public static void InstallCausalities(IEnumerable<ICausality> causalities)
        {
            ReinstateCausalities(new List<ICausality>(causalities));
        }

        public static void ClearCausalities()
        {
            while (Dispatcher.ActiveCausalities.Count > 0)
            {
                ICausality c = Dispatcher.ActiveCausalities.FirstOrDefault();
                if (c != null) Dispatcher.RemoveCausality(c);
            }
        }


        private static void CollectCausalitiesThroughRemoval(ICollection<ICausality> causalities)
        {
            while (Dispatcher.ActiveCausalities.Count > 0)
            {
                ICausality c = Dispatcher.ActiveCausalities.FirstOrDefault();
                if (c != null)
                {
                    causalities.Add(c);
                    Dispatcher.RemoveCausality(c);
                }
            }
        }

        private static void ReinstateCausalities(IList<ICausality> causalities)
        {
            for (int i = causalities.Count - 1; i >= 0; i--)
                Dispatcher.AddCausality(causalities[i]);
        }
	}
}
